﻿using StockPredictor.App_Start;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace StockPredictor.Models
{
    public class PortfolioRecordsContext : DbContext
    {
        public DbSet<PortfolioRecordModel> PortfolioRecords { get; set; }

        public PortfolioRecordsContext()
            : base("DefaultConnection")
        {
        }
    }

    [Table("Portfolio")]
    public class PortfolioRecordModel
    {
        /// <summary>
        /// Portfolio Record ID
        /// </summary>
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int PortfolioId { get; set; }
        
        /// <summary>
        /// User Id for the portfolio record
        /// </summary>
        public int UserId { get; set; }

        /// <summary>
        /// Stock Symbol for this portfolio record
        /// </summary>
        public string StockSymbol { get; set; }

        /// <summary>
        /// Full Stock name for this portfolio record (not saved to the database)
        /// </summary>
        [NotMapped]
        public string StockName { get; set; }

        /// <summary>
        /// Number of shares for this portfolio record
        /// </summary>
        [Required]
        [Display(Name = "Number of Shares")]
        public double Shares { get; set; }
    }

    public static class PortfolioUtilities
    {
        public static List<PortfolioRecordModel> GetPortfolioRecordsForUser(string userName)
        {
            PortfolioRecordsContext portfolioContext = new PortfolioRecordsContext();
            int userId = AccountUtilities.GetUserIdForUser(userName);
            var records = portfolioContext.PortfolioRecords.Where(stock => stock.UserId == userId).ToList();
            // get the full stock name for each record
            foreach (PortfolioRecordModel record in records)
            {
                record.StockName = YahooFinance.GetFullCompanyName(record.StockSymbol);
            }
            return records;
        }
    }
}